<?php
/**
 * 接口控制器
 */
namespace Admin\Controller;
use Think\Controller;
use Think\Log;
use Org\Util\Page;

class PurchaseController extends BaseController
{
	     public function index(){
        $this->display();
    }


    public function purchaseList()
    {
  
    $_listrows = I('request._listrows', '', 'trim');
        $keywords = I('request.keywords','','trim');
        if(!empty($keywords)){
            $_where['purchaseame']=array('like',"%{$keywords}%");
        }
        
        $start_time = I('request.start_time','','trim');
        $end_time = I('request.end_time','','trim');
        $str='';
        //如果两个为空，没有条件
        //否则 一个为空，一个有值，两个有值 
        if(!(empty($start_time) && empty($end_time))){ 
            $start_time = empty($start_time)?date("Y-m-d"):$start_time;
            $end_time = empty($end_time)?date("Y-m-d"):$end_time;
            if($start_time>$end_time){
                 $temp=$end_time;
                 $end_time=$start_time;
                 $start_time=$temp;
            }  
  
           $str =" and a.createtime between '".$start_time." 00:00:01' and '".$end_time." 23:59:59'"; 
        }  
        
        $str = ltrim(trim($str),'and');
        if(!empty($str)){
            $_where['_string']=$str;
        }
        $where_order['where'] = $_where;
        /*$where_order['order'] = ' last_transaction_time desc ';*/
        $where_order['listrows'] = $_listrows;
        $where_order["id"]="load_tb_div";
        $where_order["alias"]="a";
        $where_order["order"]="a.createtime desc";
        $where_order["field"]="a.*,u.user_name";
        $where_order["join"]=array("inner join ".$this->dbprefix."admin_user u on a.operationuser=u.user_id");   
        $_datalist = $this->_getListsFromModel('wx_purchase', $where_order);
    
    //判断时间是否过期，过期就将状态改为无效（找到isactive=1）
        $time = D('wx_purchase')->field('lasttime,purchaseid')->where('isactive=1')->find();
        $this->time_if_overdue($time['lasttime'],$time['purchaseid']);
        $this->assign('_datalist', $_datalist);
        $this->display(); 
    }
   
   //时间是否过期，并修改isactive=2 完成
   public  function  time_if_overdue($lasttime,$purchaseid){
       $nowtime =strtotime(date('Y-m-d H:i:s')) ;
       $endtime = strtotime($lasttime);
       if($nowtime > $endtime){
         $where['isactive']=2;
         $res = D('wx_purchase')->where('purchaseid="'.$purchaseid.'"')->save($where);
         if($res){
            return true;
         }
       }
   }

    public function add_purchase(){
       $this->display();
    }

public function addPurchase(){
    
    $data['purchaseid'] = guid() ;
       $data['purchaseame'] =I('post.username');
       $data['lasttime'] =I('post.end_time');
       $data['remark'] =I('post.remark');
       $data['isactive'] =0;
       $data['operationuser'] = $_SESSION['admin_id'];
       $data['createtime'] = date('Y-m-d H:i:s');
       $exe_scriptstr = "<script>
        setTimeout(function(){
            var win=    art.dialog.opener;
                        win._reload_currentpage_datalist('load_tb_div');
                        art.dialog.close();
        },1500);
       </script>";

       //判断日期不能小于当前日期
       if(strtotime($data['lasttime']) < time() &&  $data['isactive'] ==1){
        //添加成功后，输出文本，把js脚本一起输出，前台只要html到某个div里就能够执行js
            $this->success('添加有效采购单的结束时间不能小于当前时间！'); 
       }

     //先查询是否已近有正在采购的采购单
/*       if($data['isactive'] == 1){
               $result = D('wx_purchase')->where('isactive=1')->find();
               if($result){
                 $this->success('有正在采购的采购单，只能添加无效效采购单！'); 
               }
       }*/
       $res = D('wx_purchase')->add($data);
       if($res != false){
            //添加成功后，输出文本，把js脚本一起输出，前台只要html到某个div里就能够执行js
            $this->success('操作成功！' . $exe_scriptstr);
       }else{


           $this->success('操作失败！' . $exe_scriptstr);
       }
        $this->display();


}

    public function update_wx_purchase(){
        $map['purchaseid'] = I('get.purchaseid');
        $list = D('wx_purchase')->where($map)->find();
       if($list != flase){
        $this->assign('list',$list);
        $this->display();
       }
    }


    //判断该采购单是否开启
    public function purchase_is_isactive(){
        $map['purchaseid'] = I('post.purchaseid');
        $list = D('wx_purchase')->where($map)->find();
        if(!$list){
             $ret=array('staute'=>'error','msg'=>"该采购单不存在");
             $this->ajaxReturn($ret); 
        }
        if($list['isactive'] == 1){
             $ret=array('staute'=>'error','msg'=>"该采购单正在采购中，不能操作");
             $this->ajaxReturn($ret);
        }

         if($list['isactive'] == 2){
             $ret=array('staute'=>'error','msg'=>"该采购单已近结束，不能操作");
             $this->ajaxReturn($ret);
        }
             $ret=array('staute'=>'success','msg'=>"可以操作");
             $this->ajaxReturn($ret);
    }

    public function save_wx_purchase(){
        $map['purchaseid'] = $purchaseid = I('post.id');
           $data['purchaseame'] =I('post.username');
           $data['isactive'] =I('post.in_or_out');
           $data['lasttime'] =I('post.end_time');
           $data['remark'] =I('post.remark');
           $data['operationuser'] = $_SESSION['admin_id'];
           $data['createtime'] = date('Y-m-d H:i:s');
            $exe_scriptstr = "<script>
                    setTimeout(function(){
                        var win=    art.dialog.opener;
                                    win._reload_currentpage_datalist('load_tb_div');
                                    art.dialog.close();
                    },1500);
                    
               </script>";
          if(strtotime($data['lasttime']) < time() &&  $data['isactive'] ==1){
                //添加成功后，输出文本，把js脚本一起输出，前台只要html到某个div里就能够执行js
                $this->success('结束时间已过期，不能设置为有效！');
          }

           $res = D('wx_purchase')->where($map)->save($data);
           //如果该采购单设置为有效，那么久将别的采购单设置为无效
/*           if($data['isactive'] ==1){
            $save['isactive'] = 0;
             $result = D('wx_purchase')->where("purchaseid <> '".$purchaseid."'")->save($save);
           }*/

           if($res != flase){
                $this->success('操作成功！' . $exe_scriptstr);
            }else{
                $this->error('操作失败！' . $exe_scriptstr); 
            }
           $this->display();
  

}
  
//设置采购单状态
    public function set_purchase_isactive(){
           $map['purchaseid']  = I('get.purchaseid');
           $data['isactive'] =I('get.isactive');
           //获取改采购单的内容
           $list = D('wx_purchase')->where($map)->find();

           if(!$list){
            $this->success('该采购单不存在' ); 
           }           
          if(strtotime($list['lasttime']) < time() &&  $data['isactive'] ==1){
                //添加成功后，输出文本，把js脚本一起输出，前台只要html到某个div里就能够执行js

                $this->success('结束时间已过期，不能设置为有效！');
          }
          
          if($data['isactive'] ==1){
          //设置有效时，检测该采购单是否有商品
               $result = D('wx_purchaselist')->where($map)->find();
               if(!$result){
                $this->success('该采购单没有商品，请先添加商品！');
               }
          }
           $res = D('wx_purchase')->where($map)->save($data);
           //如果该采购单设置为有效，那么久将别的采购单设置为无效
/*           if($data['isactive'] ==1){
            $save['isactive'] = 0;
             $result = D('wx_purchase')->where("purchaseid <> '".$purchaseid."'")->save($save);
           }*/

           if($res != flase){
                $this->success('操作成功！');
            }else{
                $this->error('操作失败！'); 
            }
  

}


       public function delete_wx_purchase(){
         if(IS_GET){
            $map['purchaseid'] = I('get.id');
            $list = D('wx_purchase')->field('isactive')->where($map)->find();
            if($list['isactive'] ==1){
                 $this->success("该采购单正在采购中,不能删除！") ;
            }
            $offer_list= D('wx_offerlist')->where($map)->find();
            if(!empty($offer_list)){
                 $this->success("供应单中有该采购单记录,不能删除！") ;
            }
            $row = D('wx_purchase')->where($map)->delete();
            if($row != flase){
                $this->success("删除成功") ;
            }else{
                $this->error("删除失败") ;
            }

         }

    }
    public function all_delete_wx_purchase(){
      if(IS_POST){
        $allid = I('post.allid');
        $arrid = explode(',',$allid);
        $tmp = array();
            foreach ($arrid as $key => $value) {
              $res  =  D('wx_purchase')->where('purchaseid='.$value)->find();
              $offer_list= D('wx_offerlist')->where('purchaseid='.$value)->find();
                 if( $res['isactive'] == 0 && empty($offer_list)){
                   array_push($tmp,$value); 
                 }
                   
            }
        $_arr_id = implode(',',$tmp );
        if($_arr_id != ""){
               $where = "purchaseid in (".$_arr_id.")";
                $row = D('wx_purchase')->where($where)->delete();
                if($row != flase){
                    if(count($tmp) < count($arrid)){
                            $ret=array('staute'=>'success','msg'=>"批量操作成功!,有些采购单有效不能操作！");
                    }else{
                           $ret=array('staute'=>'success','msg'=>"批量操作成功");
                        }
                }else{
                     $ret=array('staute'=>'error','msg'=>"批量操作失败");
                }
        

         }else{
         $ret=array('staute'=>'success','msg'=>"所有的采购单都为有效，不能操作！");
         }
       $this->ajaxReturn($ret);
     }
    }




//采购单详情
    public function select_wx_purchaselist(){
    $this->display();


    }

        public function select_wx_purchaselist_list(){

     $_listrows = I('request._listrows', '', 'trim');

        
        $keywords = I('request.keywords','','trim');
        if(!empty($keywords)){
            $_where['goodsname|purchaseame']=array('like',"%{$keywords}%");
        }
        
        $start_time = I('request.start_time','','trim');
        $end_time = I('request.end_time','','trim');
        $str='';
        //如果两个为空，没有条件
        //否则 一个为空，一个有值，两个有值 
        if(!(empty($start_time) && empty($end_time))){ 
            $start_time = empty($start_time)?date("Y-m-d H:i:s"):$start_time;
            $end_time = empty($end_time)?date("Y-m-d H:i:s"):$end_time;
            
            if($start_time>$end_time){
                 $temp=$end_time;
                 $end_time=$start_time;
                 $start_time=$temp;
            }  

           $str =" and a.createtime between '".$start_time." 00:00:01' and '".$end_time." 23:59:59'"; 
        }  
        
     
        $str = ltrim(trim($str),'and');
        if(!empty($str)){
            $_where['_string']=$str;
        }
        
        $where_order['where'] = $_where;
        /*$where_order['order'] = ' last_transaction_time desc ';*/
        $where_order['listrows'] = $_listrows;
        $where_order["id"]="load_tb_div";
        $where_order["field"]="a.*,b.purchaseame,u.user_name";
        $where_order['alias']="a";
        $where_order['order']="a.createtime desc";
        $where_order["join"] =array('left join '.$this->dbprefix.'wx_purchase b on a.purchaseid=b.purchaseid','inner join '.$this->dbprefix.'admin_user u on a.operationuser=u.user_id');
      
        $_datalist = $this->_getListsFromModel('wx_purchaselist', $where_order);

        $this->assign('_datalist', $_datalist);
        $this->display(); 
 


        }


//单个采购单详情
        public function offer_details(){
      $_listrows = I('request._listrows', '', 'trim');
 // print_r($_GET['p']);exit;
        $purchaseid = I('request.purchaseid', '', 'trim');

       $keywords = I('request.keywords','','trim');
        if(!empty($keywords)){
            $_where['goodsname']=array('like',"%{$keywords}%");
        }
        if(!empty($purchaseid)){
            $_where['b.purchaseid']=$purchaseid;
        }

        $where_order['where'] = $_where;
        /*$where_order['order'] = ' last_transaction_time desc ';*/
        $where_order['listrows'] = $_listrows;
        $where_order["id"]="load_tb_div";
        $where_order["field"]="a.*,b.purchaseame,u.user_name";
        $where_order['alias']="a";
        $where_order['order']="a.number asc";
        $where_order["join"] =array('left join '.$this->dbprefix.'wx_purchase b on a.purchaseid=b.purchaseid','inner join '.$this->dbprefix.'admin_user u on a.operationuser=u.user_id');
      
        $_datalist = $this->_getListsViewSpecial('wx_purchaselist', $where_order);


        //获取采购单基本信息
        $list = D('wx_purchase')->where('purchaseid="'.$purchaseid.'"')->find();
        if($list){
          $this->assign('wx_purchase_one',$list);
        }

        $this->assign('_datalist', $_datalist);
        $this->assign('purchaseid', $purchaseid);
        $this->display('offer_details'); 

        }

    public function add_wx_purchaselist(){

        $id=I("purchaseid");   

        $id= isset($id)?$id:'';
        $id =empty($id)?'':$id; 
        $this->assign('id',$id);
        $this->display();
    }








    public  function selection_of_goods_list(){

        $id=I("post.id"); 

        $id= isset($id)?$id:'';
        $id =empty($id)?'':$id; 
        $sort=M("wx_purchase")->field("purchaseid,purchaseame")->where('isactive = 0')->select(); 
        $this->assign ( "purchase", $sort ); 
     if($id){
            $ls=D("wx_purchaselist")->alias("a")->field("a.*,c.purchaseame")->join(" left join ".$this->dbprefix."wx_purchase c on a.purchaseid= c.purchaseid")->where("a.purchaseid='$id'")->order("a.createtime desc")->select();
            $list = D('wx_purchase')->where('purchaseid = "'.$id.'"')->find();
            $this->assign("findlist",$list);
     }

        $this->assign('purchaselist',$ls);
        $this->assign("purchaseid",$id);
        $this->display();

    }



    public function update_wx_purchaselist(){
        $ret=array('staute'=>'error','msg'=>"保存失败");
        $purchase=I("purchase");
        $postdata=I("json");
        
        if(empty($purchase)||empty($postdata)){
            $ret=array('staute'=>'error','msg'=>"传输参数错误");
            $this->ajaxReturn ($ret);
            exit;
        } 
        
        $json = json_decode($postdata,true); 
        if(!is_array($json)){
            $ret=array('staute'=>'error','msg'=>"特价商品信息错误");
            $this->ajaxReturn ($ret);
            exit;
        }
        
        //对数据进行处理
         $sl=M("wx_purchaselist");
         $where['purchaseid'] = $purchase;
         $dblist= $sl->where($where)->select(); //数据库当前主题存在的记录信息;
         
         $aryadd=$arydel=$aryupd=array();
         //提交数据 是否在数据库中存在，存在更新否则增加
         foreach($json as $k=>$v){ 
            $flg=0;
            foreach ($dblist as $key=>$o){ 
              if($v["listid"]==$o['listid'] && $v["purchaseid"]==$o['purchaseid']  && $v["goodsid"]==$o['goodsid']){
                  $aryupd[]=$v;     
                  $flg=1;
                  break;
              }
            }
           if($flg==0){
                $v["listid"]=$listid;
                $aryadd[]=$v;
           }
         }
         //在数据库里存在，但是提交的数据不存在，删除数据
/*         foreach ($dblist as $key=>$o){
            $bl=0;
            foreach($json as $k=>$v){
              if($v["listid"]==$o['listid'] && $v["purchaseid"]==$o['purchaseid']&& $v["goodsid"]==$o['goodsid']){ 
                    $bl=1;
                    break;
                }
            }
            if($bl==0){
                $arydel[]=$o;
            }
         }*/
          
         $sqladd=$sqlupd=$sqldel="";
         $arysqlupd=array();  
         $time=date("Y-m-d H:i:s");
         

 
         //构建插入数据语句
         if(count($aryadd)>0){
            $sqlval=""; 
            foreach ($aryadd as $k=>$v){
                $listid=getGuid();//创建guid值
                $sqlval.=((empty($sqlval)?"":",")."('$listid','$purchase','".$v['goodsid']."','".$v['goodsname']."','".$v['unit']."','".$v['number']."','".$v['price']."',".UID.",'$time')");
            }
            $sqladd=" INSERT INTO  ".$this->dbprefix."wx_purchaselist(`listid`,`purchaseid`,`goodsid`,`goodsname`,`unit`,`number`,`price`,`operationuser`,`createtime`) values ".$sqlval;
         }
         
         //构建更新数据语句
         if(count($aryupd)>0){  
            foreach ($aryupd as $k=>$v){
                $sqlupd="update ".$this->dbprefix."wx_purchaselist set purchaseid='$purchase',goodsid='".$v['goodsid']."',goodsname='".$v['goodsname']."',unit='".$v['unit']."',number='".$v['number']."',price='".$v['price']."',operationuser='".UID."',createtime='".$time."' where listid='".$v['listid']."'";
                $arysqlupd[]=$sqlupd;
            } 
         }
        
         //构建删除数据语句
/*         if(count($arydel)>0){
            $sqlval="";
            foreach ($arydel as $k=>$v){
                $sqlval.=((empty($sqlval)?"":",").$v['listid']);
            }
            if(!empty($sqlval))
               $sqldel="delete ".$this->dbprefix."wx_purchaselist where FIND_IN_SET(listid,'".$sqlval."')";
         }*/
         
         $db=M("wx_purchaselist");
         $retadd=$retupd= $retdel=1; //默认是成功状态
         
         $db->startTrans(); //启动事务
         
         if($sqladd){
            $retadd=$db->execute($sqladd);
         } 
         
         if(count($arysqlupd)>0){
             foreach ($arysqlupd as $k=>$sql){
                if(empty($sql))continue;
                $retupd=$db->execute($sql);
                //如果失败就退出循环，失败
                if(!$retupd){
                    break;  
                }
             }
         }
         
         if($sqldel){
            $retdel=$db->execute($sqldel);
         }
         
         if($retadd && $retupd && $retdel){
            $db->commit();
            $ret=array('staute'=>'success','msg'=>"保存数据成功");
         }
         else {
            $db->rollback();
            $ret=array('staute'=>'error','msg'=>"保存数据失败");
         }  
        $this->ajaxReturn($ret);
    }

    public function delete_wx_purchaselist(){
     if(IS_GET){
        $map['listid'] = I('get.id');
        //判断该商品是否正在被采购
        $list = D('wx_purchaselist')->alias('a')->where('a.listid="'.I('get.id').'"')->join(" left join ".$this->dbprefix."wx_purchase b on a.purchaseid= b.purchaseid")->field('b.purchaseid,b.isactive')->find();
        if($list['isactive']==1 || $list['isactive']==2){
           $this->success("该商品正在采购中，不能删除！") ; 
        }
      
        $offer_list= D('wx_offerlist')->where('listid="'.I('get.id').'"')->find();
        if(!empty($offer_list)){
            $this->success("该商品在供应单中存在，不能删除!") ;
        }
        $row = D('wx_purchaselist')->where($map)->delete();
        if($row != flase){
            $this->success("删除成功") ;
        }else{
            $this->error("删除失败") ;
        }

     }

    }

    public function all_delete_wx_purchaselist(){
      if(IS_POST){
        $allid = I('post.allid');
        $arrid = explode(',',$allid);
        $tmp = array();
            foreach ($arrid as $key => $value) {
              $res  =  D('wx_purchaselist')->field('b.*')->alias('a')->where('a.listid='.$value)->join(" inner join ".$this->dbprefix."wx_purchase as b on a.purchaseid= b.purchaseid")->find();
                $offer_list= D('wx_offerlist')->where('listid="'.I('get.id').'"')->find();
                 if( $res['isactive'] == 0 && empty($offer_list)){
                   array_push($tmp,$value); 
                 }

                   
            }
        $_arr_id = implode(',',$tmp );
        if($_arr_id != ""){
               $where = "listid in (".$_arr_id.")";
                $row = D('wx_purchaselist')->where($where)->delete();
                if($row != flase){
                    if(count($tmp) < count($arrid)){
                            $ret=array('staute'=>'success','msg'=>"批量操作成功!,有些包中的商品不能操作！");
                    }else{
                           $ret=array('staute'=>'success','msg'=>"批量操作成功");
                        }
                }else{
                     $ret=array('staute'=>'error','msg'=>"批量操作失败");
                }
        

         }else{
         $ret=array('staute'=>'success','msg'=>"所有的商品都在采购单中，不能操作！");
         }
       $this->ajaxReturn($ret);
     }
    }
}


?>
